#!/bin/sh

# 设置默认环境变量
export BACKEND_HOST=${BACKEND_HOST:-localhost}
export BACKEND_PORT=${BACKEND_PORT:-8080}
export BACKEND_PROTOCOL=${BACKEND_PROTOCOL:-http}
export API_PREFIX=${API_PREFIX:-/api}

echo "🔧 配置后端服务器信息:"
echo "   Backend Host: $BACKEND_HOST"
echo "   Backend Port: $BACKEND_PORT"
echo "   Backend Protocol: $BACKEND_PROTOCOL"
echo "   API Prefix: $API_PREFIX"
echo "   Full Backend URL: $BACKEND_PROTOCOL://$BACKEND_HOST:$BACKEND_PORT"

# 使用 envsubst 替换模板中的环境变量
echo "📝 生成 nginx 配置文件..."
envsubst '${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_PROTOCOL} ${API_PREFIX}' < /etc/nginx/nginx.conf.template > /etc/nginx/nginx.conf

# 验证 nginx 配置
echo "✅ 验证 nginx 配置..."
nginx -t

if [ $? -eq 0 ]; then
    echo "✅ nginx 配置验证成功"
else
    echo "❌ nginx 配置验证失败"
    exit 1
fi

# 启动 nginx
echo "🚀 启动 Tengine..."
exec nginx -g "daemon off;" 